<template>
  <div class="comment-area wrap">
    <div class="title">
      <div>
        <el-avatar size="large" fit="contain" class="title-icon">
          <el-icon :size="28"><OfficeBuilding/></el-icon>
        </el-avatar>
      </div>
      <div>
        <h1>评论区</h1>
        <h3>{{ comments_count > 0 ? comments_count + '条评论呢' : '完全没人呢' }}</h3>
      </div>
    </div>
    <CommentAreaItem
      v-for="(item, i) in comments_info"
      :key="i"
      ref="commentAll"
      :id="item.id"
      :date="item.date"
      :name="item.name"
      :text="item.text"
      :replys_info="item.replys"
      @switch-edit-all="switchClick_All($event, i)"
    />
    <CommentAreaItemEdit :editable="editable" @reply-emits="replyTo"/>
  </div>
</template>

<script setup>
import { OfficeBuilding } from '@element-plus/icons-vue'
import { ref, computed, watch } from 'vue';
import CommentAreaItem from './CommentAreaItem.vue';
import CommentAreaItemEdit from './CommentAreaItemEdit.vue';
import { getDate } from '../features/DateTools';
import { useStore } from '../stores';
import { ElNotification } from 'element-plus';
import { v4 as uuidv4 } from 'uuid';
import { publishComment, updateArticle_support } from '../api/api'

const props = defineProps({
  articleID:{
    type: String,
    required: true
  },
  comments: {
    type: Array,
    default: []
  }
})

// 评论信息
const comments_info = ref([])
comments_info.value = props.comments

// 获取评论数
const comments_count = computed(() => {
  let count = 0
  comments_info.value.forEach(e => count += e.replys.length)
  return comments_info.value.length + count
})

// 切换输入框位置
const commentAll = ref(null)  // 外部评论dom
const editable = ref(true)    // 外部输入框可视性

// 外部输入框和外部评论交互
const switchClick_All = (val, i) => {
  // 保持外部pk状态显示与内部相反
  editable.value = !val
  // 若有内部pk显示，则关闭其余pk
  if (val) {
    commentAll.value.forEach((e, j) => {
      if(j != i) {
        e.closeAll()
      }
    })
  }
}

// 评论
const store = useStore()
const replyTo = (val) => {
  if (!store.userToken) {
    ElNotification({
      title: '评论失败',
      message: '请先登录哦 =￣ω￣=',
      type: 'error'
    })
    return false
  }
  if (!val) {
    ElNotification({
      title: '评论失败',
      message: '评论内容不能为空  ( ﹁ ﹁ ) ~→',
      type: 'error'
    })
    return false
  }
  let comment = {
    id: 'C' + uuidv4().substring(0, 6),
    articleID: props.articleID,
    userID: store.id,
    name: store.name,
    date: getDate(),
    text: val,
    replys: []
  }
  comments_info.value.push(comment)
  publishComment(comment).then(response => {
    ElNotification({
      title: '评论成功',
      message: '请继续保持友善哦(๑•̀ㅂ•́)و✧',
      type: 'success'
    })
  }).catch(error => {
    console.log(error)
    ElNotification({
      title: '评论失败',
      message: error.message,
      type: 'error'
    })
  })
}

// 监听评论数变化，及时更新服务器数据
watch(comments_count, async (newValue) => {
  emits('updateCommentsCount', newValue)
  updateArticle_support(props.articleID, { commentsCount: newValue})
  .then(response => {})
  .catch(error => console.log(error))
})
// 当评论数改变时，对应的更新文章显示评论数
const emits = defineEmits(['updateCommentsCount'])
</script>

<style scoped>
.wrap {
  padding: 3rem 1rem;
}
.title {
  margin-bottom: 2rem;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
.title > div {
  margin-left: 1rem;
}
</style>